package cn.edu.scut.suggestion;



/**
 * 查询推荐的主服务，启动该服务就可以提供查询推荐服务
 * eclipse调用参数 -Djava.library.path=/home/tian.yuchen/workspace/QuerySuggestion
 * 需要指定libICICLAS50.so的所在位置
 * 
 * @author tian.yuchen
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.RemoteException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;




public class SuggestServer {
	private int port=8888;
	private ServerSocket serverSocket;
	private ExecutorService executorService;
	private final int POOL_SIZE=10;
	
	public SuggestServer() throws IOException{
		serverSocket=new ServerSocket(port);
		executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
		System.out.println("Server Started!");
	}
	
	public void service(){
		while(true){
			Socket socket=null;
			try {
				socket=serverSocket.accept();
				executorService.execute(new DSHandler(socket));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	public static void main(String[] args) throws IOException {
		new SuggestServer().service();
	}
	
	
	
	class DSHandler implements Runnable{
		private Socket socket;
		public DSHandler(Socket socket){
			this.socket=socket;
		}
		
		private PrintWriter getWriter(Socket socket) throws IOException{
			OutputStream socketOut=socket.getOutputStream();
			return new PrintWriter(socketOut,true);
		}
		
		private BufferedReader getReader(Socket socket) throws IOException {
			InputStream socketIn=socket.getInputStream();
			return new BufferedReader(new InputStreamReader(socketIn,"GBK"));
		}
		
		public String DiverseSugg(String msg,String query){
			DiverseSuggest ds;
			try {
				ds = new DiverseSuggest();
				long start=System.currentTimeMillis();
				JSONObject resjson=ds.getDiverseSugg(query, msg);
				long cost=System.currentTimeMillis()-start;
				System.out.println("time cost: "+cost);
				if (resjson!=null){
					return resjson.toString();
				}else{
					return null;
				}
				
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
			
			
		}
		
		public String QueryExpandSugg(String srcquery){
			ExpandSuggest eg=new ExpandSuggest();
			JSONObject resj= eg.getNExpandSugg(srcquery,10);
			return resj.toString();
		}
		
		public String PhraseSugg(JSONArray data,String query){
			PhraseSuggest ps=new PhraseSuggest();
			JSONObject resj=ps.getPhraseSuggest(data, query);
			return resj.toString();
		}
		
		@Override
		public void run() {
			try {
				BufferedReader br=getReader(socket);
				PrintWriter pw=getWriter(socket);
				String msg=null;
				String allmsg="";
				String queryString=null;
				JSONArray type3data=null;
				
				int type=0;
				/*
				 * 判断查询类别，提供相应的查询推荐服务。
				 */
				while((msg=br.readLine())!=null){
					JSONObject msgJsonObject=JSONObject.fromObject(msg);
					System.out.println("type: "+msgJsonObject.get("type").toString());
					type=msgJsonObject.getInt("type");
					if(msgJsonObject.get("status").equals(0)){
						break;
					}
					
					if(type==1){
						allmsg=msgJsonObject.get("feedback").toString();
						queryString=msgJsonObject.get("query").toString();
						System.out.println("recieve msg:! "+msg);
					}else if(type==2){
						System.out.println("recieve msg:! "+msg);
						queryString=msgJsonObject.get("query").toString();
					}else if(type==3){
						type3data=msgJsonObject.getJSONArray("data");
						System.out.println("recieve msg:! "+msg);
						queryString=msgJsonObject.get("query").toString();
					}
				}
				if (type==1){
					pw.println(DiverseSugg(allmsg,queryString));
				}else if (type==2) {
					pw.println(QueryExpandSugg(queryString));
				}else if(type==3){
					pw.println(PhraseSugg(type3data, queryString));
				}
				System.out.println("out");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println("here??");
				e.printStackTrace();
			}finally{
				try{
					if(socket!=null)
						socket.close();
				}catch(IOException e){
					e.printStackTrace();
				}
			}
			
		}
		
	}
}
